package com.okb.service.impl.subscribe;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.okb.bean.CandleDataBean;
import com.okb.bean.WebSocketResponse;
import com.okb.dto.RequestTemplateDto;
import com.okb.dto.SubscriptionArgDto;
import com.okb.service.SubscribeWebSocketService;
import com.okb.utils.WebSocketClientUtil;
import com.okb.utils.WebSocketResponseParser;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;

import java.net.URI;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class BtcSocketClientExample extends WebSocketClientUtil implements SubscribeWebSocketService {
    private static final String K_URL = "wss://wspap.okx.com:8443/ws/v5/business";

    public BtcSocketClientExample() {
        super(URI.create(K_URL));
    }

    public WebSocketClient getSocketClient() {
        return this;
    }

    @Override
    protected void onSubscribe() {
        // 构建订阅请求
        RequestTemplateDto request = new RequestTemplateDto();
        request.setOp("subscribe");

        SubscriptionArgDto argBtc = new SubscriptionArgDto();
        argBtc.setChannel("candle1D");
        argBtc.setInstId("BTC-USDT");
        request.setArgs(Lists.newArrayList(argBtc));

        // 转换为 JSON 并发送
        try {
            ObjectMapper mapper = new ObjectMapper();
            String jsonRequest = mapper.writeValueAsString(request);
            log.info("发送订阅请求: " + jsonRequest);
            send(jsonRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onMessageHandle(String message) {
        WebSocketResponse webSocketResponse = JSON.parseObject(message, WebSocketResponse.class);
        // 解析 K 线数据
        List<CandleDataBean> candleDataList = WebSocketResponseParser.parseData(webSocketResponse);
        // 打印解析结果
        candleDataList.forEach(candle -> {
            String close = candle.getClose();
            Double price = Double.parseDouble(close);
            double v = price - 97689;
            double v1 = v / 97689 * 100 * 30;
            log.info("{},净值:{},盈利率:{}",candle.toString(),String.format("%.2f", v),String.format("%.2f", v1)+"%");
        });
    }

    @Override
    protected void tryReConnect(){
        new BtcSocketClientExample().startClient();
        log.info("重新建立连接成功");
    }

    public static void main(String[] args) throws InterruptedException {
        BtcSocketClientExample service = new BtcSocketClientExample();
        service.startClient();
        log.info("客户端已关闭");
    }
}
